package com.zone.vehicle.superapp.view.appmanager.tab;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;
import com.zone.lib.download.db.entity.Download;
import com.zone.lib.download.enums.AppStatusEnum;
import com.zone.lib.download.utils.DateUtils;
import com.zone.sdk.common.http.base.Result;
import com.zone.vehicle.lib.view.utils.ImageUtil;
import com.zone.vehicle.lib.view.widget.CustomDialog;
import com.zone.vehicle.superapp.R;
import com.zone.vehicle.superapp.bean.AppBean;
import com.zone.vehicle.superapp.databinding.FragmentAppManagerAppBinding;
import com.zone.vehicle.superapp.databinding.FragmentAppManagerAppLeftItemBinding;
import com.zone.vehicle.superapp.databinding.FragmentAppManagerAppRightItemBinding;
import com.zone.lib.download.enums.AppTypeEnum;
import com.zone.vehicle.superapp.model.AppManagerViewModel;
import com.zone.vehicle.superapp.model.ViewModelFactory;
import com.zone.vehicle.superapp.view.common.base.BaseFragment;
import com.zone.vehicle.superapp.view.home.detail.widget.SupperProgressbar;
import com.zone.vehicle.superapp.view.util.TimeUtils;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A fragment representing a list of Items.
 */
public class AppListFragment extends BaseFragment {

    private static final String TAG = AppListFragment.class.getSimpleName();

    private FragmentAppManagerAppBinding binding;

    private LeftAdapter leftAdapter;
    private RightAdapter rightAdapter;

    private static AppManagerViewModel viewModel;
    private static Activity activity;
    private static Map<String, DownloadListener> downloadListeners = new HashMap<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = requireActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentAppManagerAppBinding.inflate(inflater);
        viewModel = new ViewModelProvider(requireActivity(), new ViewModelFactory()).get(AppManagerViewModel.class);
        initView();
        return binding.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    private void initView(){
        leftAdapter = new LeftAdapter(new ArrayList<>());
        leftAdapter.setHasStableIds(true);
        binding.left.setAdapter(leftAdapter);
        binding.left.getItemAnimator().setChangeDuration(0);

        rightAdapter = new RightAdapter(new ArrayList<>());
        rightAdapter.setHasStableIds(true);
        binding.right.setAdapter(rightAdapter);
        binding.right.getItemAnimator().setChangeDuration(0);

        viewModel.getError().observe(getViewLifecycleOwner(), new Observer<Result>() {
            @Override
            public void onChanged(Result result) {
                if (ObjectUtils.isNotEmpty(result) && StringUtils.isNotEmpty(result.getResultMsg())) {
                    showLoginFailed(result.getResultMsg());
                }
            }
        });

        viewModel.getActivityApp().observe(getViewLifecycleOwner(), new Observer<List<AppBean>>() {
            @Override
            public void onChanged(List<AppBean> appBeans) {
                leftAdapter.setData(appBeans);
                leftAdapter.notifyDataSetChanged();
            }
        });

        viewModel.getInstalledApp().observe(getViewLifecycleOwner(), new Observer<List<AppBean>>() {
            @Override
            public void onChanged(List<AppBean> appBeans) {
                String buffer = "";
                if (ObjectUtils.isNotEmpty(appBeans) && appBeans.size() > 0) {
                    buffer = "已安装(" + appBeans.size() + ")";
                }else {
                    appBeans = new ArrayList<>();
                    buffer = "已安装(0)";
                }
                binding.count.setText(buffer);
                rightAdapter.setData(appBeans);
                rightAdapter.notifyDataSetChanged();
            }
        });

        setHandler(handler);
    }

    private void initData(){
        downloadListeners.clear();
        viewModel.getDownloadApps(activity, AppTypeEnum.APP);
        viewModel.getInstallApps(requireContext(), AppTypeEnum.APP);
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {

            switch (msg.what){
                case 1:
                    Download download = (Download)msg.obj;
                    if (download.getDownloadStatus() == AppStatusEnum.INSTALL_SUCCESS.CODE || download.getDownloadStatus() == AppStatusEnum.UNINSTALL_APP_SUCCESS.CODE){
                        viewModel.getInstallApps(requireContext(), AppTypeEnum.APP);
                    }else {
                        notifyDownload(download);
                    }
//                    if (ObjectUtils.isNotEmpty(download) && download.getAppType().equals(AppTypeEnum.APP.getName())){
//                        initData();
//                    }
            }
            return false;
        }
    });

    private static class LeftAdapter extends RecyclerView.Adapter<LeftAdapter.ViewHolder>{

        private List<AppBean> data;
        private FragmentAppManagerAppLeftItemBinding binding;

        public LeftAdapter(List<AppBean> data) {
            this.data = data;
        }

        public void setData(List<AppBean> data) {
            this.data = data;
        }

        @NotNull
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            binding = FragmentAppManagerAppLeftItemBinding.inflate(LayoutInflater.from(parent.getContext()));
            return new ViewHolder(binding.getRoot());
        }

        @Override
        public void onBindViewHolder(@NotNull final ViewHolder holder, int position) {
            if (ObjectUtils.isEmpty(data)) {
                return;
            }
            AppBean appBean = data.get(position);
            Download download = appBean.getDownload();
            holder.name.setText(appBean.getName());
//            String timeString = TimeUtils.getRecentTimeSpanByNow(DateUtils.getStringToLong(appBean.getDownload().getCreateTime()));
            String timeString = TimeUtils.formats(DateUtils.getStringToLong(appBean.getDownload().getCreateTime()));
            holder.time.setText(StringUtils.isNotBlank(timeString) ? timeString : appBean.getDownload().getCreateTime());
            holder.actions.setVisibility(View.GONE);

            ImageUtil.load(activity, holder.icon, appBean.getIconUrl());
            holder.btn_activity.setText(AppStatusEnum.get(download.getDownloadStatus()) != null ? AppStatusEnum.get(download.getDownloadStatus()).TITLE : null);
            if (download.getTotal() > 0) {
                holder.download_progress.setProgress((int) (download.getDownloadLocation() * 100 / download.getTotal()));
                holder.btn_activity.setBackgroundColor(Color.TRANSPARENT);
            } else {
                holder.btn_activity.setBackgroundResource(R.drawable.border);
                holder.download_progress.setProgress(0);
            }
            holder.more.setTag(holder.actions);
            holder.more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Object a = v.getTag();
                    if (null == a){
                        Log.e(TAG, "error more of null tag data");
                        return;
                    }
                    LinearLayout actions = (LinearLayout) a;
                    actions.setVisibility(View.VISIBLE);
                }
            });
            holder.item.setTag(R.id.tag_first, download.getCode());
            DownloadListener downloadListener = new DownloadListener() {
                @Override
                public void onDownloading(Download download) {
                    String code = (String)holder.item.getTag(R.id.tag_first);
                    if (download.getCode().equals(code)) {
                        holder.download_progress.setProgress((int) (download.getDownloadLocation() * 100 / download.getTotal()));
                        holder.btn_activity.setBackgroundColor(Color.TRANSPARENT);
                    }
                }
            };
            downloadListeners.put(download.getCode(), downloadListener);
            holder.item.setTag(R.id.tag_second, holder.actions);
            holder.item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Object a = v.getTag(R.id.tag_second);
                    if (null == a){
                        Log.e(TAG, "error more of null tag data");
                        return;
                    }
                    LinearLayout actions = (LinearLayout) a;
                    actions.setVisibility(View.GONE);
                }
            });
            holder.btn_activity.setTag(position);
            holder.btn_activity.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int p = (int) v.getTag();
                    AppBean b = data.get(p);
                    if (null == b) {
                        Log.e(TAG, "error click of null data");
                        return;
                    }
                    Download d = b.getDownload();
                    if (null == d || AppStatusEnum.get(d.getDownloadStatus()) == null) {
                        Log.e(TAG, "error click download of null download data");
                        return;
                    }
                    switch (AppStatusEnum.get(d.getDownloadStatus())) {
                        case INSTALL_SUCCESS:
                        case LIGHT_INSTALL_COMPLETE:
                            viewModel.startApp(activity, b);
                            break;
                        case DOWNLOAD_DEFAULT:
                        case DOWNLOAD_DEFAULT_LIGHT:
                        case DOWNLOAD_PAUSE:
                        case DOWNLOAD_FAIL:
                        case LIGHT_INSTALL_FAIL:
                            viewModel.downLoadApp(activity, AppStatusEnum.DOWNLOAD_PREPARE, b);

                            break;
                        case DOWNLOAD_PREPARE:
                        case DOWNLOAD_LOADING:
                            viewModel.downLoadApp(activity, AppStatusEnum.DOWNLOAD_PAUSE, b);
                            break;
                        case INSTALL_FAIL:
                            viewModel.install(activity, AppStatusEnum.INSTALL_PREPARE, b);
                            break;
                        default:
                            break;
                    }
                }
            });
            holder.delete.setTag(position);
            holder.delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int p = (int) v.getTag();
                    AppBean b = data.get(p);
                    if (null == b) {
                        Log.e(TAG, "error click of null data");
                        return;
                    }
                    showDialog(activity, b, "删除");
                }
            });
        }

        @Override
        public int getItemCount() {
            return data.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {

            private final RelativeLayout item;
            private final ImageView icon;
            private final TextView name;
            private final TextView time;
            private final SupperProgressbar download_progress;
            private final AppCompatButton btn_activity;
            private final AppCompatTextView more;
            private final LinearLayout actions;
            private final AppCompatTextView delete;

            public ViewHolder(View itemView) {
                super(itemView);
                item = itemView.findViewById(R.id.item);
                icon = itemView.findViewById(R.id.icon);
                name = itemView.findViewById(R.id.name);
                time = itemView.findViewById(R.id.time);
                download_progress = itemView.findViewById(R.id.download_progress);
                btn_activity = itemView.findViewById(R.id.btn_activity);
                more = itemView.findViewById(R.id.more);
                actions = itemView.findViewById(R.id.actions);
                delete = itemView.findViewById(R.id.delete);
            }
        }
    }

    private static class RightAdapter extends RecyclerView.Adapter<RightAdapter.ViewHolder>{

        private List<AppBean> data;

        private FragmentAppManagerAppRightItemBinding binding;

        public RightAdapter(List<AppBean> data) {
            this.data = data;
        }

        public void setData(List<AppBean> data) {
            this.data = data;
        }

        @NotNull
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            binding = FragmentAppManagerAppRightItemBinding.inflate(LayoutInflater.from(parent.getContext()));
            return new ViewHolder(binding.getRoot());
        }

        @Override
        public void onBindViewHolder(@NotNull ViewHolder holder, int position) {
            if (ObjectUtils.isEmpty(data)){
                return;
            }
            AppBean appBean = data.get(position);
            holder.name.setText(appBean.getName());
            holder.version.setText(appBean.getDownload().getVersion());
            holder.actions.setVisibility(View.GONE);
//            //设置图片大小
//            RoundedCorners roundedCorners = new RoundedCorners(50);
//            RequestOptions options = RequestOptions.bitmapTransform(roundedCorners)
//                    .placeholder(new ColorDrawable(Color.GRAY))//设置占位图
////                    .error(R.mipmap.logo_app)//设置异常图片
//                    .override(300, 300);//降低内存消耗
//            Glide.with(holder.itemView.getContext())
//                    .asBitmap()
//                    .load(appBean.getIcon())
//                    .apply(options)
//                    .into(holder.icon);
            ImageUtil.load(activity, holder.icon, appBean.getIconUrl());
            AppStatusEnum appStatusEnum = AppStatusEnum.get(appBean.getDownload().getDownloadStatus());
            if (ObjectUtils.isNotEmpty(appStatusEnum)) {
                if (appStatusEnum == AppStatusEnum.INSTALL_SUCCESS && ObjectUtils.isNotEmpty(appBean.getUpdateEntity()) ) {
                    holder.btn_activity.setText(AppStatusEnum.UPDATE.DESC);
                } else {
                    holder.btn_activity.setText(appStatusEnum.TITLE);
                }
            }
            holder.more.setTag(holder.actions);
            holder.more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Object a = v.getTag();
                    if (null == a){
                        Log.e(TAG, "error more of null tag data at installed");
                        return;
                    }
                    LinearLayout actions = (LinearLayout) a;
                    actions.setVisibility(View.VISIBLE);
                }
            });
            holder.item.setTag(holder.actions);
            holder.item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Object a = v.getTag();
                    if (null == a){
                        Log.e(TAG, "error more of null tag data at installed");
                        return;
                    }
                    LinearLayout actions = (LinearLayout) a;
                    actions.setVisibility(View.GONE);
                }
            });
            holder.btn_activity.setTag(position);
            holder.btn_activity.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int p = (int) v.getTag();
                    AppBean b = data.get(p);
                    if (null == b) {
                        Log.e(TAG, "error click of null data installed");
                        return;
                    }
                    if (((AppCompatButton)v).getText().toString().equals(AppStatusEnum.UPDATE.DESC)) {
                        viewModel.updateApp(activity, AppStatusEnum.UPDATE, b);
                    } else {
                        viewModel.startApp(activity, b);
                    }
                }
            });
            holder.delete.setTag(position);
            holder.delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int p = (int) v.getTag();
                    AppBean b = data.get(p);
                    if (null == b) {
                        Log.e(TAG, "error click of null data installed ");
                        return;
                    }
                    showDialog(activity, b, "卸载");
                }
            });
        }

        @Override
        public int getItemCount() {
            return data.size();
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        class ViewHolder extends RecyclerView.ViewHolder {

            private final RelativeLayout item;
            private final ImageView icon;
            private final TextView name;
            private final TextView version;
            private final AppCompatButton btn_activity;
            private final AppCompatTextView delete;
            private final AppCompatTextView more;
            private final LinearLayout actions;

            public ViewHolder(View itemView) {
                super(itemView);
                item = itemView.findViewById(R.id.item);
                icon = itemView.findViewById(R.id.icon);
                name = itemView.findViewById(R.id.name);
                version = itemView.findViewById(R.id.version);
                btn_activity = itemView.findViewById(R.id.btn_activity);
                delete = itemView.findViewById(R.id.delete);
                more = itemView.findViewById(R.id.more);
                actions = itemView.findViewById(R.id.actions);
            }
        }
    }

    private static void showDialog(Context context, AppBean appBean, String action){
        CustomDialog dialog = new CustomDialog(context);
        dialog.setTitle("是否确认"+action+" APP");
        dialog.setSubTitle(appBean.getName());
        dialog.setPositive("确认");
        dialog.setNegtive("取消");
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                dialog.cancel();
            }
        });
        dialog.setOnClickBottomListener(new CustomDialog.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                dialog.cancel();
                viewModel.delete(context, appBean);
            }

            @Override
            public void onNegtiveClick() {
                dialog.cancel();
            }
        });
        dialog.show();
    }

    private void notifyDownload(Download download){
        if (downloadListeners.containsKey(download.getCode())){
            downloadListeners.get(download.getCode()).onDownloading(download);
        }
    }

    interface DownloadListener {
        void onDownloading(Download download);
    }

}